import { useAuthStore } from '@/stores/auth-store'
import { login, register, logout, getUserProfile, forgotPassword, type LoginRequest, type RegisterRequest, type ForgotPasswordRequest } from '@/services/auth-service'
import { useNavigate } from '@tanstack/react-router'
import { toast } from 'sonner'

export const useAuth = () => {
  const { auth } = useAuthStore()
  const navigate = useNavigate()

  const signIn = async (data: LoginRequest) => {
    try {
      const response = await login(data)
      
      // 构建符合 AuthUser 接口的用户对象
      const authUser = {
        accountNo: response.user.accountNo,
        email: response.user.email,
        role: response.user.role,
        exp: Date.now() + 24 * 60 * 60 * 1000, // 24 hours from now
      }
      
      // 设置用户和访问令牌
      auth.setUser(authUser)
      auth.setAccessToken(response.accessToken)
      
      // 保存到localStorage
      localStorage.setItem('accessToken', response.accessToken)
      
      toast.success('Login successful!')
      return response
    } catch (error: any) {
      toast.error(error.message || 'Login failed. Please check your credentials.')
      throw error
    }
  }

  const signUp = async (data: RegisterRequest) => {
    try {
      const response = await register(data)
      
      // 构建符合 AuthUser 接口的用户对象
      const authUser = {
        accountNo: response.user.accountNo,
        email: response.user.email,
        role: response.user.role,
        exp: Date.now() + 24 * 60 * 60 * 1000, // 24 hours from now
      }
      
      // 设置用户和访问令牌
      auth.setUser(authUser)
      auth.setAccessToken(response.accessToken)
      
      // 保存到localStorage
      localStorage.setItem('accessToken', response.accessToken)
      
      toast.success('Registration successful!')
      return response
    } catch (error: any) {
      toast.error(error.message || 'Registration failed.')
      throw error
    }
  }

  const signOut = async () => {
    try {
      await logout()
      auth.reset()
      localStorage.removeItem('accessToken')
      toast.success('You have been logged out.')
      navigate({ to: '/sign-in' })
    } catch (error: any) {
      toast.error(error.message || 'Logout failed.')
      throw error
    }
  }

  const fetchUserProfile = async () => {
    try {
      const profile = await getUserProfile()
      return profile
    } catch (error: any) {
      toast.error(error.message || 'Failed to fetch user profile.')
      throw error
    }
  }

  const handleForgotPassword = async (data: ForgotPasswordRequest) => {
    try {
      await forgotPassword(data)
      toast.success(`Password reset email sent to ${data.email}`)
    } catch (error: any) {
      toast.error(error.message || 'Failed to send reset password email.')
      throw error
    }
  }

  return {
    user: auth.user,
    accessToken: auth.accessToken,
    isAuthenticated: !!auth.accessToken && !!auth.user,
    signIn,
    signUp,
    signOut,
    fetchUserProfile,
    forgotPassword: handleForgotPassword,
  }
}